package com.baidu.mpks.utils;


import com.baidu.mpks.user.domain.User;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Component;

@Component
public class SecurityUtil {
    public SecurityUtil() {
    }

    public static User getCurrentUser() {
        try {
            if (SecurityUtils.getSubject().isAuthenticated()) {
                return (User)SecurityUtils.getSubject().getPrincipal();
            }
        } catch (Throwable var1) {
        }

        return null;
    }

    public String getUserIdOrDefault(String defaultUserId) {
        User user = getCurrentUser();
        return user != null ? user.getUserId() : defaultUserId;
    }

    public static User getEncryptUser(User user) {
        if (user != null) {
            String email = user.getEmail();
            int atIndex = email.indexOf("@");
            String str = StringUtils.substring(email, 1, atIndex);
            String replaceStr = "";

            for(int i = 0; i < str.length(); ++i) {
                replaceStr = replaceStr + "*";
            }

            if (!str.equals(replaceStr)) {
                email = (new StringBuilder(email)).replace(1, atIndex, replaceStr).toString();
                user.setEmail(email);
            }

            String phoneNumber = user.getPhoneNumber();
            String phoneStr = StringUtils.substring(phoneNumber, 3, 7);
            if (!phoneStr.equals("****")) {
                phoneNumber = (new StringBuilder(phoneNumber)).replace(3, 7, "****").toString();
                user.setPhoneNumber(phoneNumber);
            }

            user.setPassword("******");
        }

        return user;
    }
}